library(plyr)
library(tidyverse)
library(sandwich)
library(emmeans)
library(stargazer)
library(magrittr)
library(gtools)
library(MASS)

# User should set the variable rd to wherever they extracted the replicationg files
# For instance, you should say 
# rd <- "my/directory/here"
# at the top of the code

s2 <- str_c(
  rd, 
  "Study 2/s2.rds"
  ) %>%
  read_rds 

ml <- str_c(
  "ans ~ ",
  c("corr_cond") %>%
    str_c(
      c("*trumpvoter",
        "*trumpvoter + cond")
      )
  ) %>% 
  map(
    ~lm(., data = s2)
  ) 

# Table 4

ml %>% 
  stargazer(
    digits = 2,
    omit.stat = c("f", "ser"),
    no.space = T,
    se = ml %>% 
      llply(function(i)
        i %>% 
          vcovHC(type = "HC1") %>% 
          diag %>% 
          sqrt),
    add.lines = list(
      c("Non Trump Voters",
      ml %>% 
      map(
        function(i)
          i %>% 
          emmeans(revpairwise ~ corr_cond | trumpvoter) %>% 
          use_series(contrasts) %>% 
          as.data.frame %>% 
          mutate(
            lab = estimate %>% 
              round(2) %>% 
              str_c(
                p.value %>% 
                  stars.pval,
                " (",
                SE %>% 
                  round(2),
                ")"
              )
          ) %>% 
          filter(
            trumpvoter == "1. Non Trump Voter"
          ) %>% 
          use_series(lab)
        ) %>% 
      unlist),
      c(
        "Trump Voters",
        ml %>%
          map(
            function(i)
              i %>% 
              emmeans(revpairwise ~ corr_cond | trumpvoter) %>% 
              use_series(contrasts) %>% 
              as.data.frame %>% 
              mutate(
                lab = estimate %>% 
                  round(2) %>% 
                  str_c(
                    p.value %>% 
                      stars.pval,
                    " (",
                    SE %>% 
                      round(2),
                    ")"
                  )
              ) %>% 
              filter(
                trumpvoter != "1. Non Trump Voter"
              ) %>% 
              use_series(lab)
        ) %>% 
        unlist
        )
      ),
    type = "text",
    column.sep.width = "2.5pt", 
    dep.var.labels.include = F,
    dep.var.caption = "DV: larger values indicate agreement",
    covariate.labels = c("Correction",
                         "Trump Support",
                         "Condition: MSNBC (Post-debate coverage)",
                         "Condition: MSNBC (No post-debate coveragee)",
                         "Condition: FNC (Post-debate coverage)",
                         "Condition: FNC (No post-debate coveragee)",
                         "Trump Support * Correction",
                         "Constant")
    )


s3 <- str_c(
  rd, 
  "Study 2/s3.rds"
  ) %>% 
  readRDS

lm3 <- s3 %>% 
  dlply(
    .(dv),
    function(i)
      lm(val ~ corr_cond * votechoicew1, 
         data = i)
    )

# Table 5

lm3 %>% 
  stargazer(
    no.space = T,
    model.numbers = F,
    digits = 2,
    align = F, 
    initial.zero = T,
    dep.var.labels.include = F,
    column.labels = c("Trump Won Debate",
                      "Trump Evaluation",
                      "Trump Vote"),
    covariate.labels = c("Correction",
                         "Trump Vote (W1)",
                         "Correction x Trump Vote (W1)",
                         "Intercept"),
    dep.var.caption = "",
    type = "text",
    omit.stat=c("f", "ser"), 
    add.lines = list(
      c(
        "Clinton supporters",
          lm3 %>% 
            map(
              function(i)
                # i <- lm3[[1]]
                
                i %>% 
                emmeans(pairwise ~ corr_cond | votechoicew1) %>% 
                use_series("contrasts") %>% 
                as.data.frame %>% 
                as.data.frame %>% 
                mutate(
                  lab = estimate %>% 
                    round(2) %>% 
                    str_c(
                      p.value %>% 
                        stars.pval,
                      " (",
                      SE %>% 
                        round(2),
                      ")"
                    )
                ) %>% 
                filter(
                  votechoicew1 == "1. Clinton"
                ) %>% 
                use_series(lab) %>% 
                as.character
            ) %>% 
          as.character
      ),
      c(
        "Trump supporters",
        lm3 %>% 
          map(
            function(i)
              i %>% 
              emmeans(pairwise ~ corr_cond | votechoicew1) %>% 
              use_series("contrasts") %>% 
              as.data.frame %>% 
              as.data.frame %>% 
              mutate(
                lab = estimate %>% 
                  round(2) %>% 
                  str_c(
                    p.value %>% 
                      stars.pval,
                    " (",
                    SE %>% 
                      round(2),
                    ")"
                  )
              ) %>% 
              filter(
                votechoicew1 != "1. Clinton"
              ) %>% 
              use_series(lab) %>% 
              as.character
          ) %>% 
          as.character
        )
      )
    )

# Table C3

str_c(
  rd,
  "/Study 2/s4_1.rds"
  ) %>%
  read_rds %>% 
  group_by(cat, val) %>% 
  tally %>% 
  mutate(prop = n %>% 
           divide_by(n %>% sum) %>% 
           multiply_by(100) %>% 
           round) %>% 
  select(-n) %>% 
  rename("Wave1" = prop) %>% 
  # now it's wave 2 by treatment
  left_join(
    str_c(
      rd,
      "Study 2/s4_1.rds" 
      ) %>% 
      read_rds %>% 
      group_by(cond, cat, val) %>%
      tally %>% 
      mutate(perc = n %>% 
               divide_by(n %>% 
                           sum) %>% 
               multiply_by(100) %>% 
               round) %>% 
      select(-n) %>% 
      ungroup %>% 
      mutate(cond = cond %>% 
               mapvalues(c("correction",
                           "nocorrection"),
                         c("w2treatment",
                           "w2control"))) %>% 
      spread(cond, perc)) %>% 
# now wave 2 total
  left_join(
    str_c(
      rd,
      "/Study 2/s4_2.rds"
      ) %>%
      read_rds %>%
      group_by(cat, val) %>% 
      tally %>% 
      mutate(perc = n %>% 
               divide_by(n %>% 
                           sum) %>% 
               multiply_by(100) %>% 
               round) %>% 
      select(-n) %>% 
      rename("Wave2Total" = perc)) %>% 
  # now wave 3 by condition
  left_join(    
    str_c(
      rd,
      "Study 2/s4_3.rds"
      ) %>%
      read_rds %>%
      group_by(cond, cat, val) %>% 
      tally %>% 
      mutate(perc = n %>% 
               divide_by(n %>% 
                           sum) %>% 
               multiply_by(100) %>% 
               round) %>% 
      select(-n) %>% 
      ungroup %>% 
      mutate(cond = cond %>% 
               mapvalues(c("correction",
                           "nocorrection"),
                         c("w3treatment",
                           "w3control"))) %>%
      spread(cond, perc)) %>% 
  # now wave 2 total
  left_join(
    str_c(
      rd,
      "/Study 2/s4_3.rds"
      ) %>%
        read_rds %>% 
        group_by(cat, val) %>% 
        tally %>% 
        mutate(perc = n %>% 
                 divide_by(n %>% 
                             sum) %>% 
                 multiply_by(100) %>% 
                 round) %>% 
        select(-n) %>% 
        rename("Wave3Total" = perc)
    ) %>% 
  mutate(
    val = val %>% 
      str_sub(4)
  ) %>% 
  set_colnames(
    c("cat", "val",
      "Wave 1", 
      "Wave 2(Control)",
      "Wave 2(Treatment)",
      "Wave 2(Total)",
      "Wave 3(Control)",
      "Wave 3(Treatment)",
      "Wave 3(Total)")
  )


# C21

op1 <- polr(as.factor(ans) ~ corr_cond*trumpvoter,
            method = "probit",
            data = s2 %>%
              filter(votechoicew1 != "2. Uncertain"))
op2 <- polr(as.factor(ans) ~ corr_cond*trumpvoter + cond,
            method = "probit",
            data = s2 %>%
              filter(votechoicew1 != "2. Uncertain"))

list(op1, op2) %>%
  stargazer(digits = 2,
            omit.stat = c("f", "ser"),
            no.space = T,
            # se = list(op1, op2) %>%
            #   llply(function(i)
            #     i %>%
            #       vcovHC(type = "HC1") %>%
            #       diag %>%
            #       sqrt),
            type = "text",
            column.sep.width = "2.5pt", 
            dep.var.labels.include = F,
            dep.var.caption = "DV: larger values indicate agreement",
            covariate.labels = c("Correction",
                                 "Trump Support",
                                 "Condition: MSNBC (Post-debate coverage)",
                                 "Condition: MSNBC (No post-debate coveragee)",
                                 "Condition: FNC (Post-debate coverage)",
                                 "Condition: FNC (No post-debate coveragee)",
                                 "Trump Support * Correction"),
            
            add.lines = list(
                        c("Clinton Voters",
                          list(
                            op1, op2
                          ) %>% 
                            map(
                              function(i)
                                i %>% 
                                emmeans(revpairwise ~ corr_cond | trumpvoter) %>% 
                                use_series(contrasts) %>% 
                                as.data.frame %>% 
                                mutate(
                                  lab = estimate %>% 
                                    round(2) %>% 
                                    str_c(
                                      p.value %>% 
                                        stars.pval,
                                      " (",
                                      SE %>% 
                                        round(2),
                                      ")"
                                    )
                                ) %>% 
                                filter(
                                  trumpvoter != "1. Non Trump Voter"
                                ) %>% 
                                use_series(lab)
                            ) %>% 
                            unlist
                        )
                        ,
                        c("Trump Voters",
                          list(
                            op1, op2
                            ) %>% 
                            map(
                              function(i)
                                i %>% 
                                emmeans(revpairwise ~ corr_cond | trumpvoter) %>% 
                                use_series(contrasts) %>% 
                                as.data.frame %>% 
                                mutate(
                                  lab = estimate %>% 
                                    round(2) %>% 
                                    str_c(
                                      p.value %>% 
                                        stars.pval,
                                      " (",
                                      SE %>% 
                                        round(2),
                                      ")"
                                    )
                                ) %>% 
                                filter(
                                  trumpvoter == "1. Non Trump Voter"
                                ) %>% 
                                use_series(lab)
                            ) %>% 
                            unlist
                          )
                        )
            )
                      


# C22

s3$val[s3$dv ==  "trumpftw3"] %<>% 
  as.numeric %>% 
  cut_number(2, labels = 1:2) %>% 
  as.numeric

op3 <- s3 %>% 
  dlply(
    .(dv),
    function(i)
      glm(
        as.factor(val) ~ corr_cond * votechoicew1, 
         data = i,
        family = binomial()
        )
    )

op3 %>%
  stargazer(digits = 2,
            omit.stat = c("f", "ser"),
            no.space = T,
            type = "text",
            column.sep.width = "2.5pt", 
            dep.var.labels.include = F,
            dep.var.caption = "DV: larger values indicate agreement",
            covariate.labels = c("No Correction",
                                 "Trump Support",
                                 "No Correction * Trump Support",
                                 "Constant"),
            add.lines = list(
              c("Clinton Voters",
                op3 %>% 
                  map(
                    function(i)
                    # i <- op3[[1]]
                      
                      i %>% 
                      emmeans(revpairwise ~ corr_cond | votechoicew1) %>% 
                      use_series(contrasts) %>% 
                      as.data.frame %>% 
                      mutate(
                        lab = estimate %>% 
                          round(2) %>% 
                          str_c(
                            p.value %>% 
                              stars.pval,
                            " (",
                            SE %>% 
                              round(2),
                            ")"
                          )
                      ) %>% 
                      filter(
                        votechoicew1 == "1. Clinton"
                      ) %>% 
                      use_series(lab)
                  ) %>% 
                  unlist
                )
              ,
              c("Trump Voters",
                op3 %>% 
                  map(
                    function(i)
                      i %>% 
                      emmeans(revpairwise ~ corr_cond | votechoicew1) %>% 
                      use_series(contrasts) %>% 
                      as.data.frame %>% 
                      mutate(
                        lab = estimate %>% 
                          round(2) %>% 
                          str_c(
                            p.value %>% 
                              stars.pval,
                            " (",
                            SE %>% 
                              round(2),
                            ")"
                          )
                      ) %>% 
                      filter(
                        votechoicew1 != "1. Clinton"
                      ) %>% 
                      use_series(lab)
                  ) %>% 
                  unlist
                )
              )
            )
            